package com.example.fridaykt.exception

import cn.dev33.satoken.exception.NotLoginException
import cn.dev33.satoken.exception.NotPermissionException
import cn.dev33.satoken.exception.NotRoleException
import cn.dev33.satoken.exception.NotSafeException
import cn.dev33.satoken.stp.StpUtil
import com.example.fridaykt.common.result.R
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

//@RestControllerAdvice("xxx.RestController")
@RestControllerAdvice
class GlobalExceptionHandlerForApi {

    val log = LoggerFactory.getLogger(GlobalExceptionHandlerForApi::class.java)

    //    // 在当前类每个方法进入之前触发的操作
    //    @ModelAttribute
    //    public void get(HttpServletRequest request) throws IOException {
    //
    //    }
    // 全局异常拦截（拦截项目中的所有异常）
    @ExceptionHandler
    fun handlerExceptions(
        e: Exception,
        request: HttpServletRequest?,
        response: HttpServletResponse?
    ): R {
        log.info("全局异常(API)---------------")
        e.printStackTrace()
        val errPre = "Failure: "

        // 不同异常返回不同状态码
        val aj: R
        if (e is NotLoginException) {               // 如果是未登录异常
            aj = R.error(50000, errPre + "未登录：" + e.message)
        } else if (e is NotRoleException) {         // 如果是角色异常
            aj = R.error(50000, errPre + "无此角色：" + e.role)
        } else if (e is NotPermissionException) {   // 如果是权限异常
            aj = R.error(50000, errPre + "无此权限：" + e.code)
        } else if (e is NotSafeException) {         // 如果是二级认证
            log.info("二级认证异常：" + e.message)
            StpUtil.openSafe(120)
            aj = R.error(50000, errPre + "二级认证：请于120秒内进行二级认证后重新访问")
        } else {    // 普通异常, 输出：500 + 异常信息
            aj = R.error(50000, errPre + e.message)
        }

        // 返回给前端
        return aj

        // 输出到客户端
//		response.setContentType("application/json; charset=utf-8"); // http说明，我要返回JSON对象
//		response.getWriter().print(new ObjectMapper().writeValueAsString(aj));
    }
}